﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;

namespace CommonLib
{
    public class Mail
    {
        /// <summary>
        /// 使用Interface设定的要发送的邮件地址,通过SMTP发送邮件
        /// </summary>
        /// <param name="toMailAddr"></param>
        public void SendMail(string strSubJect, string strBody, string toMailAddr)
        {
            MailInfo mailInfo = new MailInfo();
            //strMailSleep = cfg.AppSettings.Settings["SendMailSleepTime"].Value.Trim();
            mailInfo.EnableSSL = ConfigurationManager.AppSettings["EnableSSL"].Trim() == "Y" ? true : false;
            mailInfo.HostSSLPort = ConfigurationManager.AppSettings["SMTPPort"].Trim();
            mailInfo.MailHost = ConfigurationManager.AppSettings["SMTPServer"].Trim();
            mailInfo.MailUser = ConfigurationManager.AppSettings["ACCOUNT"].Trim();
            mailInfo.MailPassword = ConfigurationManager.AppSettings["PASSWORD"].Trim();
            mailInfo.FromAddress = ConfigurationManager.AppSettings["MailFrom"].Trim();
            mailInfo.Subject = strSubJect;
            mailInfo.Body = strBody;
            mailInfo.ToAddress = toMailAddr;
            mailInfo.CCAddress = "";
            SendMail(mailInfo);

        }

        public byte[] StringToByte(string str)
        {
            int byteLength = str.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                hex = new String(new Char[] { str[j], str[j + 1] });
                bytes[i] = HexToByte(hex);
                j = j + 2;
            }
            return bytes;
        }

        private byte HexToByte(string hex)
        {
            if (hex.Length > 2 || hex.Length <= 0)
                throw new ArgumentException("hex must be 1 or 2 characters in length");
            byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return newByte;
        }

        public void SendMail(MailInfo mailInfo)
        {
            try
            {
                if (string.IsNullOrEmpty(mailInfo.MailHost))
                {
                    throw new Exception("MailHost不能为空");
                }
                if (string.IsNullOrEmpty(mailInfo.MailUser))
                {
                    throw new Exception("MailUser不能为空");
                }
                if (string.IsNullOrEmpty(mailInfo.MailPassword))
                {
                    throw new Exception("MailPassword不能为空");
                }
                if (string.IsNullOrEmpty(mailInfo.ToAddress))
                {
                    throw new Exception("ToAddress不能为空");
                }
                //Comm cc = new Comm();
                //Attachment AT;
                MailMessage mail = new MailMessage();
                string[] arrMailTo;

                string[] arrMailCC;

                mail.From = new MailAddress(mailInfo.FromAddress);
                arrMailTo = mailInfo.ToAddress.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string mailAddr in arrMailTo)
                {
                    mail.To.Add(mailAddr);
                }
                arrMailCC = mailInfo.CCAddress.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string mailAddr in arrMailCC)
                {
                    mail.CC.Add(mailAddr);
                }


                mail.Subject = mailInfo.Subject;
                mail.Body = mailInfo.Body;
                mail.IsBodyHtml = false;
                mail.BodyEncoding = Encoding.GetEncoding("UTF-8");
                mail.Priority = MailPriority.Normal;
                if (mailInfo.attachmentFilename != null && mailInfo.attachmentFilename != "")
                {
                    string[] svFilename = mailInfo.attachmentFilename.Split('|');
                    string[] svStream = mailInfo.attachmentStream.Split('|');
                    for (int i = 0; i < svFilename.Length; i++)
                    {
                        mail.Attachments.Add(new Attachment(new System.IO.MemoryStream(StringToByte(svStream[i].ToString())), svFilename[i].ToString()));
                    }
                }

                SmtpClient MySmtp = null;
                string svSSL_PORT = mailInfo.HostSSLPort;
                if (svSSL_PORT == "")
                {
                    MySmtp = new SmtpClient(mailInfo.MailHost);
                }
                else
                {
                    MySmtp = new SmtpClient(mailInfo.MailHost, int.Parse(svSSL_PORT)); //--new SmtpClient("smtp.gmail.com", 587);

                }
                if (mailInfo.EnableSSL == true)
                {
                    MySmtp.EnableSsl = true;
                    MySmtp.Credentials = new System.Net.NetworkCredential(mailInfo.MailUser, mailInfo.MailPassword);
                }
                MySmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                MySmtp.Send(mail);
                MySmtp = null;
                mail.Dispose();

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

    }

    public struct MailInfo
    {
        public string FromAddress;
        public string ToAddress;
        public string CCAddress;
        public string Subject;
        public string Body;
        public string attachmentStream;
        public string attachmentFilename;

        public bool EnableSSL;
        public string HostSSLPort;
        public string MailHost;
        public string MailUser;
        public string MailPassword;
    }
}
